<template>
	<view>

		<view class="page">
			<view class="cardView">
				<view class="remarkContent">{{remarkContent}}</view>
				<mpopupHeaderItem label="申请人" :value="assignList.operatorName" height="90px" />



				<mpopupHeaderRadioItem label="组别号" :custom-class="'custom-align'" height="90px"
					:custom-style="{ padding: '20rpx' }">
					<input class="centered-input" v-model="assignList.groupNumber" placeholder="请输入组别号" />
				</mpopupHeaderRadioItem>


				<mpopupHeaderRadioItem :show-bottom-border="true" label="现场核查时间" height="90px"
					:custom-class="'custom-align'" :custom-style="{ padding: '20rpx' }">
					<view class="example-body">
						<uni-datetime-picker @change="handleDateRangeChange" v-model="dataChange" type="daterange"
							@maskClick="maskClick" rangeSeparator="至" />
					</view>
				</mpopupHeaderRadioItem>
			</view>

			<view class="cardView">
				<uni-title type="h2" title="核查组成员" align="center"></uni-title>
				<view class="table-container">
					<uni-table border empty-text="暂无验证记录">
						<!-- 独占行实现方案 -->
						<uni-tr class="group-title-row">
							<uni-td colspan="5" align="center" class="custom-header">正选组</uni-td>
						</uni-tr>
						<uni-tr style="background-color: #e9f1fe">
							<uni-th width="20%" align="center">级别</uni-th>
							<uni-th width="20%" align="center">姓名</uni-th>
							<uni-th width="20%" align="center">审查证号</uni-th>
							<uni-th width="20%" align="center">工作单位</uni-th>
							<uni-th width="20%" align="center">手机/工作电话</uni-th>
						</uni-tr>
						<!--表格 -->
						<uni-tr v-for="(item,index) in assignList.checkTeamEditZList" :key="index">
							<uni-td align="center">{{ item.level }}</uni-td>
							<uni-td align="center">{{ item.fullName }}</uni-td>
							<uni-td align="center">{{ item.checkNumber }}</uni-td>
							<uni-td align="center">{{ item.workUnit }}</uni-td>
							<uni-td align="center">{{ item.phone }}</uni-td>


							</uni-td></uni-tr>
					</uni-table>
				</view>

				<view class="table-container">
					<uni-table border empty-text="暂无验证记录">
						<!-- 独占行实现方案 -->
						<uni-tr class="group-title-row">
							<uni-td colspan="5" align="center" class="custom-header">备选组</uni-td>
						</uni-tr>
						<uni-tr style="background-color: #e9f1fe">
							<uni-th width="20%" align="center">级别</uni-th>
							<uni-th width="20%" align="center">姓名</uni-th>
							<uni-th width="20%" align="center">审查证号</uni-th>
							<uni-th width="20%" align="center">工作单位</uni-th>
							<uni-th width="20%" align="center">手机/工作电话</uni-th>
						</uni-tr>
						<!--表格 -->
						<uni-tr v-for="(item,index) in assignList.checkTeamEditBList" :key="index">
							<uni-td align="center">{{ item.level }}</uni-td>
							<uni-td align="center">{{ item.fullName }}</uni-td>
							<uni-td align="center">{{ item.checkNumber }}</uni-td>
							<uni-td align="center">{{ item.workUnit }}</uni-td>
							<uni-td align="center">{{ item.phone }}</uni-td>


							</uni-td></uni-tr>
					</uni-table>
				</view>
				<!-- 添加更多 -->
				<view class="dashed" @click="showAddMemberDialog">
					<text style="font-size: 20rpx;">+点此添加更多不符合项目</text>
				</view>

			</view>


			<!-- 修改实际派出情况部分 -->
			<view class="cardView">
				<uni-title type="h2" title="实际派出情况" align="center"></uni-title>

				<uni-forms ref="baseForm" label-position="top">
					<!-- 组长选择 -->
					<uni-forms-item label="组长" required>
						<uni-data-select v-model="assignList.groupLeader" :localdata="leaderOptions" placeholder="请选择组长"
							@change="handleLeaderChange"></uni-data-select>
					</uni-forms-item>

					<!-- 组员选择 -->
					<uni-forms-item label="组员" required>
						<uni-data-select v-model="assignList.teamMembers" :localdata="memberOptions" multiple
							placeholder="请选择组员" @change="handleMemberChange"></uni-data-select>
					</uni-forms-item>
				</uni-forms>
			</view>


			<view class="cardView">
				<uni-title type="h2" title="相关人员/单位签字盖章" align="center"></uni-title>
				<view class="dashed-box">
					<view class="custom-title">
						<view class="custom-text">
							经办人签名
						</view>
						<signInput :initialImage="assignList.checkPersonnelSignOne" bgColor="#ffffff"
							@signToUrl="signToUrl"></signInput>
					</view>

					<!-- 确认日期 -->
					<view class="custom-dateText">
						<text @click="openDatePicker('checkSignDateOne')"
							class="custom-text-bottom">{{ this.assignList.checkSignDateOne || '选择日期' }}</text>
					</view>

				</view>

				<view class="dashed-box">
					<view class="custom-title">
						<view class="custom-text">
							监督人签名
						</view>
						<signInput :initialImage="assignList.centerPersonSign" bgColor="#ffffff"
							@signToUrl="signToUrl2"></signInput>
					</view>

					<!-- 确认日期 -->
					<view class="custom-dateText">
						<text @click="openDatePicker('centerPersonDate')"
							class="custom-text-bottom">{{ this.assignList.centerPersonDate || '选择日期' }}</text>
					</view>

				</view>

			</view>

			<view class="cardView">
				<uni-title type="h3" title="批准人意见" align="left"></uni-title>

				<view class="full-width-container">
					<textarea @input="handleInput" v-model="this.assignList.approverOpinion" class="full-width-textarea"
						placeholder="请编辑评价意见" :maxlength="500"></textarea>
				</view>
				<view class="dashed-box">
					<view class="custom-title">
						<view class="custom-text">
							经办人签名
						</view>
						<signInput :initialImage="assignList.approverPersonSign" bgColor="#ffffff"
							@signToUrl="signToUrl3"></signInput>
					</view>

					<!-- 确认日期 -->
					<view class="custom-dateText">
						<text @click="openDatePicker('approverPersonDate')"
							class="custom-text-bottom">{{ this.assignList.approverPersonDate || '选择日期' }}</text>
					</view>

				</view>

			</view>



		</view>
		<view v-if="editStatus!='FALSE'" class="button-container">
			<view class="button-save">
				<button style="flex: 1;" type="primary" @click="submitForm('1')">提交派遣人员名单</button>
			</view>
			<view class="button-child">

				<button style="flex: 1;margin-right: 5px;" type="primary" @click="submitForm('0')">保存</button>
				<button style="flex: 1; margin-left: 5px;" type="warn" @click="goHome">返回工单创建页</button>

			</view>
		</view>

		<uni-popup ref="addMemberPopup" type="dialog">
			<view class="member-form-popup">
				<uni-title style="margin-bottom: 20px;" type="h2" title="新增核查组员名单" align="center"></uni-title>

				<uni-forms label-position="top" ref="memberForm" :model="memberForm">
					<uni-forms-item label="分组" required>
						<uni-data-select v-model="memberForm.group" :localdata="groupOptions" placeholder="请选择分组" />
					</uni-forms-item>

					<uni-forms-item label="级别" required>
						<uni-easyinput v-model="memberForm.level" placeholder="请输入级别" />
					</uni-forms-item>

					<uni-forms-item label="姓名" required>
						<uni-easyinput v-model="memberForm.fullName" placeholder="请输入姓名" />
					</uni-forms-item>

					<uni-forms-item label="审查证号">
						<uni-easyinput v-model="memberForm.checkNumber" placeholder="请输入审查证号" />
					</uni-forms-item>

					<uni-forms-item label="工作单位">
						<uni-easyinput v-model="memberForm.workUnit" placeholder="请输入工作单位" />
					</uni-forms-item>

					<uni-forms-item label="手机/工作电话" required>
						<uni-easyinput v-model="memberForm.phone" placeholder="请输入联系方式" type="number" />
					</uni-forms-item>

					<view class="form-buttons">
						<button class="form-btn cancel" @click="closeMemberPopup">取消</button>
						<button class="form-btn submit" @click="submitMemberForm">提交</button>
					</view>
				</uni-forms>
			</view>
		</uni-popup>


		<!-- 添加日期选择弹窗 -->
		<uni-popup ref="datePopup" type="dialog">
			<uni-popup-dialog mode="base" title="选择日期" @confirm="handleDialogConfirm" @close="handleDialogClose">
				<uni-datetime-picker type="date" @change="handleDateChange" />
			</uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	import signInput from "@/components/am-sign-input/am-sign-input.vue"
	import mpopupHeaderItem from "@/components/mpopup-header-item.vue"
	import mpopupHeaderRadioItem from "@/components/mpopup-header-radio-item.vue"
	import mpopupTable from "@/components/mpopup-table.vue"
	import signItem from '@/components/sign-item/sign-item.vue'

	import {
		getformat,
		getProject,
		addMedical,
		getMedicalDict,
		addResultList,
		medicalGetInfo,
		medicalUpdate,
		foodProductionAdd,
		foodProductionInfo
	} from '@/api/order'
	import {
		getFoodReport
	} from '@/api/report.js'
	export default {
		components: {
			mpopupHeaderRadioItem,
			mpopupHeaderItem,
			signInput
		},
		data() {
			return {
				// 新增以下两个字段
				selectedLeader: '', // 选中组长
				selectedMembers: [], // 选中组员
				remarkContent: '',
				dataChange: [],
				memberForm: {
					group: '',
					level: '',
					fullName: '',
					checkNumber: '',
					workUnit: '',
					phone: ''
				},
				groupOptions: [{
						text: '正选组',
						value: 'z'
					},
					{
						text: '备选组',
						value: 'b'
					}
				],
				editDateType: '',
				tempDate: '',
				assignList: {
					operatorName: '',
					enterpriseDate: '',
					enterpriseSign: '',
					evaluationOpinion: '',
					checkStartTime: "", //现场核查开始时间
					checkEndTime: "", //现场核查结束时间
					groupLeader: "", //组长
					teamMembers: "", //组员
					checkPersonnelSignOne: "", //经办人签字
					checkSignDateOne: "", //经办人签字日期
					centerPersonSign: "", //监督人签字
					centerPersonDate: "", //监督人签字日期
					approverOpinion: "", //批准人意见
					approverPersonSign: "", //批准人签字
					approverPersonDate: "", //批准人签字日期
					createBy: "管理员", //系统管理员
					auditStatus: "", //暂存给0,提交给1 
					checkTeamEditZList: [], //正选组
					checkTeamEditBList: [], //备选组
					workOrderId: '',
					orderCategory: ''
				},
				editStatus: 'ADD'

			}
		},
		props: {

			uploadUrl: {
				type: String,
				default: "https://8954wg323mw0.vicp.fun/app/upload/uploadFile"
			},

		},
		onLoad(options) {
			if (options.editStatus != null) {
				const editStatus = decodeURIComponent(options.editStatus);
				const workOrderId = decodeURIComponent(options.workOrderId);

				this.assignList.workOrderId = workOrderId;
				this.editStatus = editStatus;

				this.getfoodProductionInfo(workOrderId);
			} else {
				if (options.orderData) {
					const orderData = JSON.parse(decodeURIComponent(options.orderData));

					const orderid = decodeURIComponent(options.workOrderId);

					this.assignList.operatorName = orderData.operatorName;
					this.assignList.workOrderId = orderid;
					this.assignList.orderCategory = orderData.orderCategory;
					this.assignList.bidType = orderData.bidType;
				}
			}

			this.getMedicalDict('check_staff_form_wenan');

		},
		computed: {
			// 所有可用人员（正备选组合并）
			allMembers() {
				return [
					...this.assignList.checkTeamEditZList,
					...this.assignList.checkTeamEditBList
				].filter(m => m?.fullName?.trim()); // 增加有效性过滤
			},
			// 组长选项（不排除已选组员）
			leaderOptions() {
				return this.allMembers.map(m => ({
					text: m.fullName, // 只显示姓名
					value: m.fullName
				}));
			},

			// 组员选项（不排除已选组长）
			memberOptions() {
				return this.allMembers.map(m => ({
					text: m.fullName, // 只显示姓名
					value: m.fullName
				}));
			}
		},
		// 在数据更新时调用统计方法
		watch: {

		},
		methods: {

			handleInput(e) {
				// 手动截断字符（解决部分机型兼容性问题）
				this.assignList.approverOpinion = e.target.value.slice(0, 500);
			},
			// 获取医疗器械工单详情
			async getfoodProductionInfo(orderId) {
				const id = {
					workOrderId: orderId
				}
				const res = await foodProductionInfo(id);
				if (res.code === 0) {

					this.assignList = res.data;

					// 修改后（正确方式）
					this.dataChange = [
						new Date(this.assignList.checkStartTime).getTime(),
						new Date(this.assignList.checkEndTime).getTime()
					];
				}
			},
			handleLeaderChange(value) {
				console.log('选中组长:', value);
				// 自动清除组员中的重复项
				//    this.assignList.selectedMembers = this.assignList.selectedMembers.filter(
				//     name => name !== value
				//   );
			},

			handleMemberChange(values) {
				console.log('选中组员:', values);
				// 自动清除组长中的重复项
				//  if (values.includes(this.assignList.selectedLeader)) {
				//    this.assignList.selectedLeader = '';
				//  }
			},
			// 提交方法
			submitForm(status) {
				if (this.editStatus == 'FALSE') {
					uni.showToast({
						title: '当前处于查看状态',
						icon: 'none'
					});
				}
				if (this.editStatus === 'EDIT') {
					this.UPDATE(status);
				}

				if (this.editStatus === 'ADD') {
					this.ADD(status);
				}



			},
			//添加
			async ADD(status) {
				this.assignList.auditStatus = status;
				console.log(this.assignList)

				const res = await foodProductionAdd(this.assignList);
				if (res.code === 0) {
					// 显示成功提示 
					uni.showToast({
						title: '提交成功',
						icon: 'success',
						duration: 1500
					});

				// 关闭当前页面，跳转到工单页
				this.$closeAndRedirect({
				  url: '/pages/work/history/index'
				});
				} else {
					// 处理失败情况
					uni.showToast({
						title: res.msg || '提交失败',
						icon: 'none'
					});
				}

			},
			//修改
			async UPDATE(status) {
				this.assignList.auditStatus = status;
				console.log(this.assignList)

				const res = await foodProductionAdd(this.assignList);
				if (res.code === 0) {
					// 显示成功提示
					uni.showToast({
						title: '提交成功',
						icon: 'success',
						duration: 1500
					});

				
				// 关闭当前页面，跳转到工单页
				this.$closeAndRedirect({
				  url: '/pages/work/history/index'
				});
				} else {
					// 处理失败情况
					uni.showToast({
						title: res.msg || '提交失败',
						icon: 'none'
					});
				}

			},

			// 打开日期选择器
			openDatePicker(type) {
				this.editDateType = type;
				this.$refs.datePopup.open();
			},
			// 日期变化暂存
			handleDateChange(e) {
				this.tempDate = e ? new Date(e) : null;
			}, // 弹窗确认
			// 修改handleDialogConfirm方法
			handleDialogConfirm() {
				if (this.tempDate) {
					const year = this.tempDate.getFullYear();
					const month = (this.tempDate.getMonth() + 1).toString().padStart(2, '0');
					const day = this.tempDate.getDate().toString().padStart(2, '0');
					const formattedDate = `${year}-${month}-${day}`;
					if (this.editDateType === 'checkSignDateOne') {
						this.assignList.checkSignDateOne = formattedDate;
					} else if (this.editDateType === 'centerPersonDate') {
						this.assignList.centerPersonDate = formattedDate;
					} else if (this.editDateType === 'approverPersonDate') {
						this.assignList.approverPersonDate = formattedDate;
					}

				}

				this.$refs.datePopup.close();
			},
			// 弹窗关闭
			handleDialogClose() {
				this.currentEditType = null;
				this.tempDate = null;
				this.$refs.datePopup.close();
			},

			/**
			 * @param {Object} e
			 * 经办人
			 */
			signToUrl(e) {
				if (e.error_code && e.error_code === '201') {
					uni.showToast({
						title: e.msg,
						icon: 'none'
					})
					return
				}
				// 1. 解析响应数据（假设 e.data 是 JSON 字符串）
				const response = JSON.parse(e.data)
				this.assignList.checkPersonnelSignOne = response.data;
			},
			/**
			 * @param {Object} e
			 * 监督人
			 */
			signToUrl2(e) {
				if (e.error_code && e.error_code === '201') {
					uni.showToast({
						title: e.msg,
						icon: 'none'
					})
					return
				}
				const response = JSON.parse(e.data)
				console.log(response.data);
				this.assignList.centerPersonSign = response.data;

			},
			/**
			 * @param {Object} e
			 * 批准人
			 */
			signToUrl3(e) {
				if (e.error_code && e.error_code === '201') {
					uni.showToast({
						title: e.msg,
						icon: 'none'
					})
					return
				}
				const response = JSON.parse(e.data)
				this.assignList.approverPersonSign = response.data;


			},
			goHome() {
				this.$tab.navigateBack();
			},
			// 显示弹窗
			showAddMemberDialog() {
				this.$refs.addMemberPopup.open()
			},

			// 关闭弹窗
			closeMemberPopup() {
				this.$refs.addMemberPopup.close()
				this.resetMemberForm()
			},

			// 重置表单
			resetMemberForm() {
				this.memberForm = {
					group: '',
					level: '',
					fullName: '',
					checkNumber: '',
					workUnit: '',
					phone: ''
				}
			},
			// 提交表单
			async submitMemberForm() {
				const valid = await this.$refs.memberForm.validate()
				if (!valid) return

				const newMember = {
					...this.memberForm
				}
				delete newMember.group // 移除分组字段

				if (this.memberForm.group === 'z') {
					this.assignList.checkTeamEditZList.push(newMember)
				} else {
					this.assignList.checkTeamEditBList.push(newMember)
				}

				this.closeMemberPopup();
				uni.showToast({
					title: '添加成功'
				})

			},
			handleDateRangeChange(e) {
				// 类型验证（避免小程序端数据类型不一致）
				if (Array.isArray(e)) {
					this.assignList.checkStartTime = this.formatDate(e[0])
					this.assignList.checkEndTime = this.formatDate(e[1])
				} else if (e?.detail?.value) { // 兼容微信小程序事件对象
					const [start, end] = e.detail.value
					this.assignList.checkStartTime = this.formatDate(start)
					this.assignList.checkEndTime = this.formatDate(end)
				}
				console.log('起始时间:', this.assignList.checkStartTime)
				console.log('结束时间:', this.assignList.checkEndTime)
			},
			formatDate(timestamp) {
				// 时间戳转日期字符串（示例格式：2025-03-25）
				return new Date(timestamp).toISOString().split('T')[0]
			},
			//获取字典值
			async getMedicalDict(type) {
				try {
					const res = await getMedicalDict(type)

					// 增加响应状态判断
					if (res.code === 0) {

						switch (type) {
							case 'check_staff_form_wenan':
								this.remarkContent = res.data[0].remark
								break;
							case '2017':

							case 'bid_type':
								this.valueOptions = res.data.map(item => ({
									text: item.label,
									value: String(item.value) // 确保字典值转为字符串
								}));
								break;
							case 'mode_of_operation':
								this.modeOptions = res.data.map(item => ({
									text: item.label,
									value: String(item.value) // 确保字典值转为字符串
								}));


								break;

							default:
								return;
						}
					} else {
						throw new Error(res?.data?.msg || '接口返回异常')
					}

				} catch (error) {
					uni.showToast({
						title: error.message || '获取分类失败',
						icon: 'none',
						duration: 2000
					})
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.page {
		background-color: #e9f1fe;
		padding: 20px;
	}

	.cardView {
		font-size: 15px;
		margin-bottom: 10px;
		padding: 15px;
		background: #ffffff;
		border-radius: 8px;
		box-shadow: 0 2px 12px rgba(0, 0, 0, 0.12);
	}

	/* 虚线容器 */
	.dashed-box {
		width: 100%;
		margin: 24rpx auto;
		padding: 12rpx;
		border: 2rpx dashed #333;
		border-radius: 10rpx;
		background: #fff;
		margin-bottom: 40px;
		position: relative;



		.custom-title {
			display: flex;
			margin-top: 10px;
			justify-content: center;
			align-items: center;
			margin-bottom: 10px;
			/* 保持原有下边距 */

		}

		.custom-text {

			color: black;
			font-size: 16px;
			font-weight: bold;
			text-align: right;
			margin-right: 20px;
		}


		.custom-dateText {
			display: flex;
			margin: 20px;
			justify-content: flex-end;
			/* 子元素居左 */
		}

		.custom-text-bottom {
			border-bottom: 1px solid #000;
			padding-bottom: 2px;
			padding-left: 10px;
			color: #0055ff;
			font-size: 16px;

			font-weight: bold;
			padding-right: 10px;
			margin-left: 4px;
			margin-right: 4px;
		}

	}

	.full-width-textarea {
		width: 100%;
		background-color: #e9f1fe;
		height: 200rpx;
		padding: 20rpx;
		box-sizing: border-box;
		border: 1rpx solid #e5e5e5;
		border-radius: 8rpx;
		font-size: 19rpx;
		line-height: 1.6;
	}

	.button-container {
		display: flex;
		background-color: #ffffff;
		width: 100%;
		padding: 10px;
		flex-direction: column;
		/* 垂直排列 */

		.button-save {
			margin-bottom: 10px;
		}

		.button-child {
			display: flex;
			flex-direction: row;
			/* 垂直排列 */

		}
	}

	/* 表格容器 */
	.table-container {
		max-height: 60vh;

		.term-table {
			font-size: 28rpx;

			.title-cell {
				font-weight: bold;
				color: #2d8cf0;
			}

			.content-cell {
				height: 180rpx;

				scroll-view {
					height: 100%;
					line-height: 1.6;
				}
			}
		}
	}


	/* 虚线容器 */
	.dashed {

		border: 2rpx dashed #0055ff;
		border-radius: 10rpx;
		background: #e5ecff;
		height: 50px;
		/* 设置为flex布局 */
		display: flex;
		/* 水平居中 */
		justify-content: center;
		margin: 15px;
		/* 垂直居中 */
		align-items: center;
	}

	.centered-input {
		width: 100%;
		text-align: center;
		height: 80rpx;
		line-height: 80rpx;
		/* 保持与高度一致 */
		font-size: 16rpx;
		border-radius: 12rpx;
	}

	.remarkContent {
		padding: 10px;
		font-size: 15px;
	}

	.member-form-popup {
		background: #fff;
		padding: 30rpx;
		border-radius: 16rpx;
		width: 90vw;
	}

	.form-buttons {
		display: flex;
		justify-content: space-between;
		margin-top: 40rpx;

		.form-btn {
			flex: 0 48%;
			height: 80rpx;
			line-height: 80rpx;

			&.cancel {
				background: #f0f0f0;
				color: #666;
			}

			&.submit {
				background: #007AFF;
				color: white;
			}
		}
	}

	/* 调整表单项样式 */
	::v-deep .uni-forms-item__label {
		font-weight: bold;
		color: #333;
	}

	::v-deep .uni-easyinput__content {
		border-radius: 8rpx;
	}
</style>